package com.exception.resolver;


import com.dto.JsonResult;
import com.exception.DisabledLoginException;
import com.exception.ParamException;
import com.exception.PermissionException;
import com.utils.HttpUtils;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Yadasu
 * @Description 全局控制层异常处理器
 * @Date 2020/10/7 16:16
 * @Version 1.0
 */
@Slf4j
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object o, Exception e) {
        log.info("异常处理器处理异常...");
        if (o instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            log.info("出现异常的Controller控制器为：" + handlerMethod.getBean());
            log.info("出现异常的Controller控制器方法为：" + handlerMethod.getMethod());
        }
        //存在异常
        if (null != e) {
            log.info(e.getMessage()); //异常信息
            //登录异常
            if (e instanceof ParamException || e instanceof MalformedJwtException || e instanceof DisabledLoginException || e instanceof BadCredentialsException) {
                HttpUtils.writeJson(resp, JsonResult.buildFailure(401, e.getMessage()), 401);
            } else if (e instanceof PermissionException) { //权限异常
                HttpUtils.writeJson(resp, JsonResult.buildFailure(403, e.getMessage()), 403);
            } else if (e instanceof AccessDeniedException) {
                HttpUtils.writeJson(resp, JsonResult.buildFailure(403, "您的权限不足"), 403);
            } else {
                HttpUtils.writeJson(resp, JsonResult.buildFailure(500, "服务端异常"), 500);
            }
        }
        return null;
    }
}
